<template>
  <component
    v-if="chat_show && init_data_end"
    :applicationAvailable="applicationAvailable"
    :is="currentTemplate"
    v-model:application_profile="application_profile"
    v-loading="loading"
  />
</template>

<script setup lang="ts">
import { ref, onBeforeMount, computed, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import useStore from '@/stores'
import { useI18n } from 'vue-i18n'
const { locale } = useI18n({ useScope: 'global' })
const route = useRoute()
const { application, user } = useStore()
const { params: { accessToken } } = route as any

const components: any = import.meta.glob('@/views/diy/chat/**/index.vue', { eager: true })

const is_auth = ref<boolean>(false)
const loading = ref(false)
const show_history = ref(false)
const application_profile = ref<any>({})
const init_data_end = ref<boolean>(false)
const applicationAvailable = ref<boolean>(true)


const currentTemplate = computed(() => {
  const name = `/src/views/diy/chat/pc/index.vue`
  return components[name].default
})
/**
 * 是否显示对话
 */
 const chat_show = computed(() => {
  if (!init_data_end.value) return false;
  if (!applicationAvailable.value) return true;
  if (!application_profile.value) return false;
  return !application_profile.value.authentication || is_auth.value;
});

function getAppProfile() {
  return application.asyncGetAppProfile(loading).then((res: any) => {
    locale.value = 'zh-CN'
    show_history.value = res.data?.show_history
    application_profile.value = {
      ...res.data,
    }
  })
}
function getAccessToken(token: string) {
  return application.asyncAppAuthentication(token, loading).then(() => {
    return getAppProfile()
  })
}

onBeforeMount(() => {
  user.changeUserType(2)
  Promise.all([user.asyncGetProfile(), getAccessToken(accessToken)])
    .catch(() => {
      applicationAvailable.value = false
    })
    .finally(() => (init_data_end.value = true))
})

onBeforeUnmount(() => {
  user.changeUserType(1)
  init_data_end.value = false
})
</script>
